<template>
  <div
    :style="{
      height: height,
      width: width,
      border: bordered ? '#d9d9d9 1px solid' : 'none',
      'border-radius': bordered ? '4px' : '0px'
    }"
  >
    <s-scroll>
      <a-tree
        v-bind="$attrs"
        :check-strictly="true"
        :checkable="true"
        :checked-keys="selected"
        :tree-data="treeData"
        :field-names="{
          children: 'children',
          title: labelField,
          key: valueField
        }"
        :expanded-keys="expandedKeys"
        @expand="expand"
        @check="onCheck"
      />
    </s-scroll>
  </div>
</template>
<script>
import { buildTree, findAllChildrenKeys, findInTree } from '@/utils/tree'
export default {
  name: 'STree',
  props: {
    modelValue: {
      required: false
    },
    valueType: {
      type: String,
      required: false,
      default: 'Array'
    },
    url: {
      type: String,
      required: false
    },
    expandAll: {
      type: Boolean,
      default: true
    },
    bordered: {
      type: Boolean,
      default: true
    },
    checkChildren: {
      type: Boolean,
      default: true
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '400px'
    },
    selectUrl: {
      type: String,
      required: false
    },
    code: {
      type: String,
      required: false
    },
    labelField: {
      type: String,
      default: 'text'
    },
    valueField: {
      type: String,
      default: 'value'
    },
    keyField: {
      type: String,
      default: 'id'
    },
    parentKeyField: {
      type: String,
      default: 'parentId'
    }
  },
  emits: ['change', 'update:modelValue'],
  data() {
    return { visible: false, treeData: [], selected: [], expandedKeys: [] }
  },
  watch: {
    selectUrl() {
      this.selected = []
      this.loadSelected()
    },
    url(val) {
      this.treeData = []
      this.loadData()
    },
    code(val) {
      this.treeData = []
      this.loadData()
    },
    modelValue(val) {
      this.selected = this.initSelectValue()
    }
  },
  created() {
    this.selected = this.initSelectValue()
    this.loadData()
  },
  methods: {
    initSelectValue() {
      if (this.valueType == 'Array') {
        return this.modelValue
      }
      let array = []
      if (this.modelValue) {
        array = this.modelValue.split(',')
      }
      return array
    },
    getLabel() {
      const labels = []
      if (this.selected && this.selected.length > 0) {
        this.selected.forEach((item) => {
          const r = findInTree(this.treeData, this.valueField, item)
          if (r) {
            labels.push(r[this.labelField])
          }
        })
      }
      return labels.toString()
    },
    expand(e) {
      this.expandedKeys = e
    },
    loadSelected() {
      if (this.selectUrl) {
        this.$api.GET(this.selectUrl).then((res) => {
          if (res.data) {
            const keys = []
            res.data.forEach((item) => {
              keys.push(item[this.valueField])
            })
            this.selected = keys
            let checked = keys
            if (!checked) {
              checked = []
            }
            let checkedStr = ''
            checked.forEach((item) => {
              if (checkedStr == '') {
                checkedStr = item
              } else {
                checkedStr = checkedStr + ',' + item
              }
            })
            this.$emit('update:modelValue', this.valueType == 'Array' ? checked : checkedStr)
            this.$emit('change', checked)
          }
        })
      }
    },
    getTreeData() {
      return this.treeData
    },
    loadData() {
      this.expandedKeys = []
      if (this.url) {
        this.$api.GET(this.url).then((res) => {
          if (res.data) {
            this.treeData = buildTree(res.data, this.parentKeyField, this.keyField)
            if (this.expandAll && res.data) {
              res.data.forEach((item) => {
                this.expandedKeys.push(item[this.valueField])
              })
            }
          }
        })
      } else if (this.code) {
        this.$api.GET('/data/tree/item/selectListByGroupId', { groupId: this.code }).then((res) => {
          if (res.data) {
            this.treeData = buildTree(res.data, this.parentKeyField, this.keyField)
            if (this.expandAll && res.data) {
              res.data.forEach((item) => {
                this.expandedKeys.push(item[this.valueField])
              })
            }
          }
        })
      }
    },
    onCheck(checkedKeys, e) {
      let checked = checkedKeys.checked
      if (!checked) {
        checked = []
      }
      if (e && e.checked && this.checkChildren) {
        const p = e.node.eventKey
        // 使其子节点check
        const array = findAllChildrenKeys(this.treeData, this.valueField, p)
        if (array.length > 0) {
          array.forEach((item) => {
            if (!checked.includes(item)) {
              checked.push(item)
            }
          })
        }
      }
      let checkedStr = ''
      checked.forEach((item) => {
        if (checkedStr == '') {
          checkedStr = item
        } else {
          checkedStr = checkedStr + ',' + item
        }
      })
      this.$emit('update:modelValue', this.valueType == 'Array' ? checked : checkedStr)
      this.$emit('change', checked)
    }
  }
}
</script>
